package com.fone.player.storage;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.fone.player.entity.Download;
import com.fone.player.util.L;

/**
 * 
 * 文件下载表适配器
 * 
 * @author wangyang
 * @since 2014年4月29日
 */
public class FileDownloadDataBaseAdapter implements IFoneDatabase {
	private static final String TAG = FileDownloadDataBaseAdapter.class
			.getSimpleName();
	private static final FileDownloadDataBaseAdapter mInstance = new FileDownloadDataBaseAdapter();
	private OperateDataBaseTemplate mGeneralDataBaseTemplate = OperateDataBaseTemplate
			.getInstance();

	private FileDownloadDataBaseAdapter() {

	}

	public static FileDownloadDataBaseAdapter getInstance() {
		return mInstance;
	}

	/**
	 * 
	 * 添加下载信息
	 * 
	 * @param download
	 *            下载对象
	 * @return int 操作结果<br>
	 *         1插入成功<br>
	 *         -1 插入异常
	 * 
	 */
	public int addDownload(Download download) {
		synchronized (TAG) {
			int id = -1;
			try {
				mGeneralDataBaseTemplate.open();

				// 添加
				long newId = 0;
				ContentValues contentValues = new ContentValues();
				contentValues.put(FILE_DOWNLOAD_FILE_NAME,
						download.getDownloadFileName());
				contentValues.put(FILE_DOWNLOAD_VERSION_NAME,
						download.getDownloadVersionName());
				contentValues.put(FILE_DOWNLOAD_VERSION_CODE,
						download.getDownloadVersionCode());
				contentValues.put(FILE_DOWNLOAD_URL, download.getDownloadUrl());
				contentValues.put(FILE_DOWNLOAD_ALREADY_SIZE,
						download.getDownloadAlreadySize());
				contentValues.put(FILE_DOWNLOAD_TOTAL_SIZE,
						download.getDownloadTotalSize());
				contentValues.put(FILE_DOWNLOAD_STORAGE_PATH,
						download.getDownloadStoragePath());
				contentValues.put(FILE_DOWNLOAD_STATE_TYPE,
						download.getDownloadStateType());
				contentValues
						.put(FILE_DOWNLOAD_IS_NOTIFICATION, download
								.getDownloadIsShowRunningNotification() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_INSTALL,
						download.getDownloadIsInstall() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_ERROR_TOAST,
						download.getDownloadIsErrorToast() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_REPORT_TYPE,
						download.getDownloadReportType());
				contentValues.put(FILE_DOWNLOAD_TYPE,
						download.getDownloadType());
				contentValues.put(FILE_DOWNLOAD_IS_LIMIT_SPEED,
						download.getDownloadIsLimitSpeed() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_UPGRADE,
						download.getDownloadIsUpgrade() ? 1 : 0);
				newId = mGeneralDataBaseTemplate.insert(TB_FILE_DOWNLOAD, null,
						contentValues);

				id = newId > 0 ? 1 : -1;
			} catch (Exception e) {
				e.printStackTrace();
				L.v(TAG, e.getMessage());
				return -1;
			} finally {

				mGeneralDataBaseTemplate.close();
			}
			return id;
		}
	}

	/**
	 * 
	 * 更新下载信息
	 * 
	 * @param download
	 *            下载对象
	 * @return int 操作结果<br>
	 *         1插入成功<br>
	 *         -1 插入异常
	 * 
	 */
	public int updateDownload(Download download) {
		L.v(TAG, "updateDownload", "start");
		synchronized (TAG) {
			int id = -1;
			try {
				mGeneralDataBaseTemplate.open();

				// 添加
				long newId = 0;

				ContentValues contentValues = new ContentValues();
				contentValues.put(FILE_DOWNLOAD_FILE_NAME,
						download.getDownloadFileName());
				contentValues.put(FILE_DOWNLOAD_VERSION_NAME,
						download.getDownloadVersionName());
				contentValues.put(FILE_DOWNLOAD_VERSION_CODE,
						download.getDownloadVersionCode());
				contentValues.put(FILE_DOWNLOAD_STATE_TYPE,
						download.getDownloadStateType());
				contentValues.put(FILE_DOWNLOAD_ALREADY_SIZE,
						download.getDownloadAlreadySize());
				contentValues.put(FILE_DOWNLOAD_TOTAL_SIZE,
						download.getDownloadTotalSize());
				contentValues.put(FILE_DOWNLOAD_STORAGE_PATH,
						download.getDownloadStoragePath());
				contentValues
						.put(FILE_DOWNLOAD_IS_NOTIFICATION, download
								.getDownloadIsShowRunningNotification() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_INSTALL,
						download.getDownloadIsInstall() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_ERROR_TOAST,
						download.getDownloadIsErrorToast() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_REPORT_TYPE,
						download.getDownloadReportType());
				contentValues.put(FILE_DOWNLOAD_TYPE,
						download.getDownloadType());
				contentValues.put(FILE_DOWNLOAD_IS_LIMIT_SPEED,
						download.getDownloadIsLimitSpeed() ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_IS_UPGRADE,
						download.getDownloadIsUpgrade() ? 1 : 0);
				StringBuilder where = new StringBuilder();
				where.append(FILE_DOWNLOAD_URL);
				where.append("=?");
				newId = mGeneralDataBaseTemplate.update(TB_FILE_DOWNLOAD,
						contentValues, where.toString(),
						new String[] { download.getDownloadUrl() });

				id = newId > 0 ? 1 : -1;
			} catch (Exception e) {
				e.printStackTrace();
				L.e(TAG, "updateDownload", e.getMessage());
				return -1;
			} finally {

				mGeneralDataBaseTemplate.close();
			}
			return id;
		}
	}

	/**
	 * 
	 * 更新是否升级
	 * 
	 * @param downloadUrl
	 *            下载连接
	 * @param isUpgrade
	 *            是否已经升级过
	 * @return int 操作结果<br>
	 *         1插入成功<br>
	 *         -1 插入异常
	 * 
	 */
	public int updateDownloadIsUpgrade(String downloadUrl, boolean isUpgrade) {
		L.v(TAG, "updateDownloadIsUpgrade", "start");
		synchronized (TAG) {
			int id = -1;
			try {
				mGeneralDataBaseTemplate.open();

				// 更新
				long newId = 0;

				ContentValues contentValues = new ContentValues();
				contentValues.put(FILE_DOWNLOAD_IS_UPGRADE, isUpgrade ? 1 : 0);
				contentValues.put(FILE_DOWNLOAD_STATE_TYPE,
						Download.DOWNLOAD_STATE_NOT_DOWNLOAD);
				StringBuilder where = new StringBuilder();
				where.append(FILE_DOWNLOAD_URL);
				where.append("=?");
				newId = mGeneralDataBaseTemplate.update(TB_FILE_DOWNLOAD,
						contentValues, where.toString(),
						new String[] { downloadUrl });

				id = newId > 0 ? 1 : -1;
			} catch (Exception e) {
				e.printStackTrace();
				L.e(TAG, "updateDownloadIsUpgrade", e.getMessage());
				return -1;
			} finally {

				mGeneralDataBaseTemplate.close();
			}
			return id;
		}
	}

	/**
	 * 
	 * 判断当前下载是否存在
	 * 
	 * @return Download 下载对象
	 */
	public boolean isDownloadExist(Download download) {
		StringBuilder sql = new StringBuilder("select * from ");
		sql.append(TB_FILE_DOWNLOAD);
		sql.append(" where ");
		sql.append(FILE_DOWNLOAD_URL);
		sql.append("='");
		sql.append(download.getDownloadUrl());
		sql.append("'");
		Cursor cursor = null;
		try {
			mGeneralDataBaseTemplate.open();
			cursor = mGeneralDataBaseTemplate.select(sql.toString());

			if (cursor == null) {
				return false;
			}
			if (cursor.getCount() > 0) {
				return true;
			}

		} catch (Exception e) {

		} finally {
			if (cursor != null) {

				cursor.close();

			}
			mGeneralDataBaseTemplate.close();

		}
		return false;
	}

	/**
	 * 
	 * 获得指定下载状态类型的列表
	 * 
	 * @return stateType 下载状态
	 */
	public List<Download> getDownloadList(int stateType) {
		StringBuilder sql = new StringBuilder("select * from ");
		sql.append(TB_FILE_DOWNLOAD);
		switch (stateType) {
		case Download.DOWNLOAD_STATE_ALL:
			break;
		case Download.DOWNLOAD_STATE_ALL_NOT_DOWNLOAD:
			sql.append(" where ");
			sql.append(FILE_DOWNLOAD_STATE_TYPE);
			sql.append("!=");
			sql.append(Download.DOWNLOAD_STATE_FINISH);
			break;
		default:
			sql.append(" where ");
			sql.append(FILE_DOWNLOAD_STATE_TYPE);
			sql.append("=");
			sql.append(stateType);
			break;
		}

		Cursor cursor = null;
		List<Download> downloadList = null;
		try {
			mGeneralDataBaseTemplate.open();
			cursor = mGeneralDataBaseTemplate.select(sql.toString());

			if (cursor == null) {
				return null;
			}

			downloadList = new ArrayList<Download>();
			// 读取数据
			while (cursor.moveToNext()) {
				Download download = getDownloadByCursor(cursor);
				if (download != null) {
					downloadList.add(download);
				}
			}

		} catch (Exception e) {
		} finally {
			if (cursor != null) {

				cursor.close();

			}
			mGeneralDataBaseTemplate.close();

		}
		return downloadList;
	}

	/**
	 * 
	 * 根据URL获取下载对象
	 * 
	 * @return url 下载url
	 */
	public Download getDownload(String url) {
		StringBuilder sql = new StringBuilder("select * from ");
		sql.append(TB_FILE_DOWNLOAD);
		sql.append(" where ");
		sql.append(FILE_DOWNLOAD_URL);
		sql.append("=?");

		Cursor cursor = null;
		Download download = null;
		try {
			mGeneralDataBaseTemplate.open();
			cursor = mGeneralDataBaseTemplate.select(sql.toString(),
					new String[] { url });

			if (cursor == null) {
				return null;
			}

			// 读取数据
			while (cursor.moveToNext()) {
				download = getDownloadByCursor(cursor);
			}

		} catch (Exception e) {
		} finally {
			if (cursor != null) {

				cursor.close();

			}
			mGeneralDataBaseTemplate.close();

		}
		return download;
	}

	/**
	 * 
	 * 根据URL删除下载对象
	 * 
	 * @return url 下载url
	 */
	public void deleteDownload(String url) {
		StringBuilder where = new StringBuilder();
		where.append(FILE_DOWNLOAD_URL);
		where.append("=?");
		try {
			mGeneralDataBaseTemplate.open();
			mGeneralDataBaseTemplate.delete(TB_FILE_DOWNLOAD, where.toString(),
					new String[] { url });

		} catch (Exception e) {
		} finally {
			mGeneralDataBaseTemplate.close();
		}
	}

	private Download getDownloadByCursor(Cursor cursor) {
		Download download = new Download();
		download.setDownloadId(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_ID)));
		download.setDownloadFileName(cursor.getString(cursor
				.getColumnIndex(FILE_DOWNLOAD_FILE_NAME)));
		download.setDownloadVersionName(cursor.getString(cursor
				.getColumnIndex(FILE_DOWNLOAD_VERSION_NAME)));
		download.setDownloadVersionCode(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_VERSION_CODE)));
		download.setDownloadAlreadySize(cursor.getLong(cursor
				.getColumnIndex(FILE_DOWNLOAD_ALREADY_SIZE)));
		download.setDownloadTotalSize(cursor.getLong(cursor
				.getColumnIndex(FILE_DOWNLOAD_TOTAL_SIZE)));
		download.setDownloadStateType(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_STATE_TYPE)));
		download.setDownloadStoragePath(cursor.getString(cursor
				.getColumnIndex(FILE_DOWNLOAD_STORAGE_PATH)));
		download.setDownloadUrl(cursor.getString(cursor
				.getColumnIndex(FILE_DOWNLOAD_URL)));
		download.setDownloadIsShowRunningNotification(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_IS_NOTIFICATION)) == 1);
		download.setDownloadIsInstall(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_IS_INSTALL)) == 1);
		download.setDownloadIsErrorToast(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_IS_ERROR_TOAST)) == 1);
		download.setDownloadReportType(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_REPORT_TYPE)));
		download.setDownloadType(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_TYPE)));
		download.setDownloadIsLimitSpeed(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_IS_LIMIT_SPEED)) == 1);
		download.setDownloadIsUpgrade(cursor.getInt(cursor
				.getColumnIndex(FILE_DOWNLOAD_IS_UPGRADE)) == 1);
		return download;
	}
}
